package controllers;

import models.*;
import notifiers.Mails;
import play.*;
import play.data.validation.*;
import play.libs.*;
import play.*;
import play.mvc.*;
import java.util.*;

import play.cache.*;
import org.joda.time.DateTime;
import org.joda.time.Years;

public class Registration extends Controller {
	
	static final int[] STARS = {1,2,3,4,5};
	
	public static void captcha(String id) {
	    Images.Captcha captcha = Images.captcha();
	    String code = captcha.getText("#000000");
	    Cache.set(id, code, "10mn");
	    renderBinary(captcha);
	}
	
	public static void indexPrivate() {
		String randomID = Codec.UUID();
		render(randomID);
    }
	
	public static void indexCommercial() {
		String randomID = Codec.UUID();
		int[] stars = Registration.STARS;
		
		render(randomID, stars);
    }
	
	
	//calculates someones age
	public static int getAge(int date, int month, int year){
		
		Calendar today = Calendar.getInstance();
		int yearToday = today.get(Calendar.YEAR);
		int monthToday = today.get(Calendar.MONTH);
		
		int age = yearToday - year;
		
		if((monthToday+1) < month){
			age--;
		}
		else if((monthToday+1) == month && today.get(Calendar.DAY_OF_MONTH)< date){
			age--;
		}
		
	    return age;
	}
	
	public static void registerPrivate(
			//validates email
			@Required
	        @Email
			String email,
	        @Required
	        @Email
	        @Equals("email")
	        String emailConfirm,
	        //validates password and ensures min passwordlength
	        @Required
	        @MinSize(5)
	        String password,
	        @Required
	        @MinSize(5)
	        @Equals("password")
	        String passwordConfirm,
	        @Required
	        String firstname,
	        @Required
	        String lastname,
	        //Date dateOfBirth,
	        @Required
	        String street,
	        @Required	        
	        Integer streetNumber,
	        @Required
	        Integer zipcode,
	        @Required
	        String city,
	        @Required(message="Please type the code") String code, 
	        String randomID,
	        @Required
	        String birthDateString,
	        @Phone
	        String Phone
	        ) {
	
		
			int[] birthDate = Tools.splitDate(birthDateString);

			//calculates the age of the user who wants to register
			int age = getAge(birthDate[2], birthDate[1], birthDate[0]);
			
			/*
			 * some more validation rules
			 */
			
			/*
			 * validates personal information
			 */
			
			//ensures email is available
			if(!User.isEmailAvailable(email)){
				validation.addError("email", "Email is already in use");
			}
			
			//ensures street number is in some normal range
	        validation.range(streetNumber,1,999);
	        //ensures user are older than 16 and not dead for centuries
	        validation.min(age,18);
	        //ensures phone is a real phonenumber
	        validation.phone(Phone);
	        
	        //validation of the captcha
	        validation.equals(code, Cache.get(randomID)).message("Invalid code. Please type it again");
	           
	        //Handle errors
	        if(validation.hasErrors() || !User.isEmailAvailable(email)) {	        	
	        	params.flash(); // add http parameters to the flash scope
	            validation.keep(); // keep the errors for the next request
	            indexPrivate();	        	
	        	//render("@index", randomID, days, months, years);
	        }
	        
	        //create new user (missing -> just display atm)
	        PrivateOfferer user = new PrivateOfferer(email, password);
	        user.firstname = firstname;
	        user.lastname = lastname;
	        user.street = street;
	        user.streetNumber = streetNumber;
	        user.zipcode = zipcode;
	        user.city = city;
	        user.dateOfBirth = new GregorianCalendar(birthDate[0], birthDate[1]-1, birthDate[2]).getTime();
	        user.save();
	        Mails.welcome(user);
	        
	        // Ok, display the created user
	        Cache.delete(randomID);
	        render(email, firstname, lastname);
	}	
	
	public static void registerCommercial(
			//validates hotel information
			@Required
			String hotelname,
			@URL
			String hotellink,
			Integer stars,
			//validates email
			@Required
	        @Email
			String email,
	        @Required
	        @Email
	        @Equals("email")
	        String emailConfirm,
	        //validates password and ensures min passwordlength
	        @Required
	        @MinSize(5)
	        String password,
	        @Required
	        @MinSize(5)
	        @Equals("password")
	        String passwordConfirm,
	        @Required
	        String firstname,
	        @Required
	        String lastname,
	        //Date dateOfBirth,
	        @Required
	        String street,
	        @Required	        
	        Integer streetNumber,
	        @Required
	        Integer zipcode,
	        @Required
	        String city,
	        @Required(message="Please type the code") String code, 
	        String randomID,
	        @Required
	        String birthDateString,
	        @Phone
	        String Phone
	        ) {
	
			int[] birthDate = Tools.splitDate(birthDateString);

			//calculates the age of the user who wants to register
			int age = getAge(birthDate[2], birthDate[1], birthDate[0]);
			
			/*
			 * some more validation rules
			 */
			
			/*
			 * validates personal information
			 */
			
			//ensures email is available
			if(!User.isEmailAvailable(email)){
				validation.addError("email", "Email is already in use");
			}
			
			//ensures street number is in some normal range
	        validation.range(streetNumber,1,999);
	        //ensures user are older than 16 and not dead for centuries
	        validation.min(age,18);
	        //ensures phone is a real phonenumber
	        validation.phone(Phone);
	        
	        //validation of the captcha
	        validation.equals(code, Cache.get(randomID)).message("Invalid code. Please type it again");
	           
	        //Handle errors
	        if(validation.hasErrors() || !User.isEmailAvailable(email)) {	        	
	        	params.flash(); // add http parameters to the flash scope
	            validation.keep(); // keep the errors for the next request
	            indexCommercial();	        	
	        	//render("@index", randomID, days, months, years);
	        }
	        
	        //create new user (missing -> just display atm)
	        CommercialOfferer user = new CommercialOfferer(email, password);
	        user.hotelname = hotelname;
	        user.hotellink = hotellink;
	        user.stars = stars;
	        user.firstname = firstname;
	        user.lastname = lastname;
	        user.street = street;
	        user.streetNumber = streetNumber;
	        user.zipcode = zipcode;
	        user.city = city;
	        user.dateOfBirth = new GregorianCalendar(birthDate[0], birthDate[1]-1, birthDate[2]).getTime();
	        user.save();
	        Mails.welcome(user);
	        
	        // Ok, display the created user
	        Cache.delete(randomID);
	        render(hotelname, email, firstname, lastname);
	}	
}
